package com.jgsu.farm.controller;

import com.jgsu.farm.entity.User;
import com.jgsu.farm.service.ImageService;
import com.jgsu.farm.service.Match_ImageService;
import com.jgsu.farm.service.UserService;
import com.jgsu.farm.utils.*;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("farm/sysuser/user/expert")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    FileUploadUtil fileUploadUtil;

    /**
     * 删除专家用户
     * */
    @DeleteMapping(value = "/delete", produces = "application/json")
    public CommonResult deleteRoleByPhone(@RequestParam("userid") Integer userid) {
        int count = userService.deleteUserByID(userid);
        if (count == 1) {
            log.info("删除成功,userid{}",userid);
            return CommonResult.success(ResultCode.SUCCESS);
        } else {
            log.error("不存在id为{}的用户，删除失败",userid);
            return CommonResult.failed(ResultCode.FAILED);
        }
    }

    /**
     * 修改专家用户信息
     * */
    @PutMapping(value = "/update", produces = "application/json")
    public CommonResult updateExpert(Integer userid,String password,Integer role,String name,String nickname,String phone,
                                String email,Integer address,String postcode,String introduction,Integer state,
                                    MultipartFile photo){
        try {
            String uploadFile = fileUploadUtil.upload(photo);
            Integer updateExpert = userService.modifyExpertMsg(userid,password,role,name,nickname,phone,email,address,
                    postcode,uploadFile,introduction,state);
            if (updateExpert == 1){
                return CommonResult.success(ResultCode.SUCCESS);
            }else {
                return CommonResult.failed(ResultCode.DATA_Not_Exist_ERROR);
            }
        } catch (IOException e) {
            log.error("头像文件上传失败");
            return CommonResult.failed(ResultCode.DATA_Not_Exist_ERROR);
        }
    }
    /**
     * 基于动态SQL的查询专家用户数据,可根据state查询
     * */
    @GetMapping(produces = "application/json")
    public CommonResult<PageInfo<User>> findExpertWithState(@RequestParam(value = "state",required = false) Integer state,
                                                            @RequestParam(value = "page",required = false,defaultValue = "1")int page
            ,@RequestParam(value = "pagesize",required = false,defaultValue = "10")int pagesize){
        PageInfo<User> expertList = userService.FindExpertListByState(2,state,page,pagesize);
        return CommonResult.success(expertList);
    }
}
